package com.weiyi.admin.config;

import com.weiyi.admin.dto.ResourceRoleDTO;
import com.weiyi.admin.models.ums.service.UmsAdminService;
import com.weiyi.admin.models.ums.service.UmsResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import weiyi.security.config.Component.StaticResourceRoleSource;
import weiyi.security.config.Component.dynamicSecurity.DynamicSecurityService;
import weiyi.security.config.SecurityConfig;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;


@Configuration
@EnableWebSecurity
public class AdminSecurityConfig extends SecurityConfig {
    @Autowired
    UmsAdminService umsAdminService;

    @Autowired
    UmsResourceService umsResourceService;

    @Bean
    public UserDetailsService userDetailsService(){
        return username -> umsAdminService.loadUserByUserName(username);
    }


    public StaticResourceRoleSource staticResourceRoleSource(){
        return () -> {
            // Map<String, List<String>>
            // 调用业务逻辑类查询资源对应角色信息
            List<ResourceRoleDTO> list= umsResourceService.getAllResourceRole();
            //查出ResourceRole之后将其封装到Map中
            Map<String, List<String>> map=new HashMap<>();
            for (ResourceRoleDTO resourceRoleDTO : list) {
                List<String> roleNamelist= resourceRoleDTO.getRoleList()
                        .stream()
                        .map(role-> role.getName())
                        .collect(Collectors.toList());

                map.put(resourceRoleDTO.getUrl(),roleNamelist);
            }
            return map;
        };
    }


    @Bean("dynamicSecurityService")
    public DynamicSecurityService dynamicSecurityService(UmsResourceService umsResourceService) {
        return () -> {
            Map<RequestMatcher, List<ConfigAttribute>> map = new ConcurrentHashMap<>();

            List<ResourceRoleDTO> list= umsResourceService.getAllResourceRole();
            for (ResourceRoleDTO resource : list) {
                // 通配符匹配器
                map.put(new AntPathRequestMatcher(resource.getUrl()),
                        // 所有角色信息
                        resource.getRoleList().stream()
                                .map(role-> new org.springframework.security.access.SecurityConfig(role.getName()))
                                .collect(Collectors.toList())
                );
            }
            return map;
        };
    }


}
